package com.erdos.message.vo.converter;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public class FloatConverter implements Converter {

	@SuppressWarnings("unchecked")
	public boolean canConvert(Class type) {		
		return type.equals(float.class) || type.equals(Float.class);
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {		
		if(source==null || source.equals(Float.NaN) || source.equals(Float.MIN_VALUE)) {
			writer.setValue("");
		}  else { 
			String strVal = String.valueOf(source);
			if(strVal.indexOf("E")>0){//是科学计数法
				String strIntVal = MessageConstant.DATA_FORMAT_INT.format(source);//整数部分
				float decimalVal = (Float)source - Float.valueOf(strIntVal);//小数部分数值
				if(decimalVal >= MessageConstant.MIN_DECIMAL_VALUE){//小数部分有值
					writer.setValue(MessageConstant.DATA_FORMAT_DECIMAL.format(source));
				}else{//小数部分无值
					writer.setValue(strIntVal);
				}
			}else{
				writer.setValue(strVal);
			}			
		}			
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {		
		if(StringUtils.isNotBlank(reader.getValue())) {
			return Float.valueOf(reader.getValue().trim());
		} else {
			return null;
		}		
	}

}
